package com.example.HelloSpace.viewmodels;

import android.app.Application;
import android.os.AsyncTask;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import androidx.work.Constraints;
import androidx.work.ExistingWorkPolicy;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.OutOfQuotaPolicy;
import androidx.work.WorkManager;

import com.example.HelloSpace.database.AppDatabase;
import com.example.HelloSpace.database.entities.SpaceMissionEntity;
import com.example.HelloSpace.worker.SendMessageWorker;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class SubscribedMissionsViewModel extends AndroidViewModel {
    private final MutableLiveData<List<SpaceMissionEntity>> subscribedMissions;
    private final AppDatabase db;
    private WorkManager workManager;

    public SubscribedMissionsViewModel(@NonNull Application application, AppDatabase db) {
        super(application);
        //insertSampleData();
        this.db = db;
        subscribedMissions = new MutableLiveData<>();
        loadSubscribedMissions();
        scheduleMessage(10);
    }

    private void loadSubscribedMissions() {
        db.spaceMissionDao().getAllMissions().observeForever(spaceMissions -> {
            subscribedMissions.postValue(spaceMissions);
        });
    }

    public LiveData<List<SpaceMissionEntity>> getSubscribedMissions() {
        return subscribedMissions;
    }

    /**
     * 计算从当前时间到指定发射时间的倒计时，并转换为BJT时间。
     */
    public String calculateCountdown(Instant launchTimeUtc) {
        ZonedDateTime utcLaunchTime = ZonedDateTime.ofInstant(launchTimeUtc, ZoneId.of("UTC"));
        ZonedDateTime bjLaunchTime = utcLaunchTime.withZoneSameInstant(ZoneId.of("Asia/Shanghai")); // 转换到BJT
        ZonedDateTime nowBJ = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));

        Duration diff = Duration.between(nowBJ, bjLaunchTime);

        long days = diff.toDays();
        long hours = diff.toHours() % 24;
        long minutes = diff.toMinutes() % 60;
        long seconds = diff.getSeconds() % 60;

        if (diff.isNegative()) {
            return String.format("T+%02d:%02d:%02d:%02d", -days, -hours, -minutes, -seconds);
        } else {
            return String.format("T-%02d:%02d:%02d:%02d", days, hours, minutes, seconds);
        }
    }

    public void insertSampleData() {
        List<SpaceMissionEntity> sampleMissions = Arrays.asList(
                new SpaceMissionEntity(25020301, "电子号 | IoT 4 You and Me (Kinéis 16-20)", Instant.now().plus(Duration.ofDays(5)), true, "2月下旬", "预计"),
                new SpaceMissionEntity(25020302, "猎鹰9号 | Starlink Group 10-12", Instant.now().plus(Duration.ofDays(10)), false, "取消待定", "取消"),
                new SpaceMissionEntity(25020303, "长征二号F | 神州二十号", Instant.now().plus(Duration.ofDays(15)), true, "3月下旬", "成功")
        );
        // 创建一个与样本任务数量相匹配的数组
        SpaceMissionEntity[] array = new SpaceMissionEntity[sampleMissions.size()];

        // 使用 toArray 方法并传入正确类型的数组
        SpaceMissionEntity[] missionsArray = sampleMissions.toArray(array);

        new Thread(() -> db.spaceMissionDao().insert(missionsArray)).start();
    }

    public void scheduleMessage(long delayMillis) {
//        Constraints constraints = new Constraints.Builder()
//                .build();
        OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(SendMessageWorker.class)
                .setInitialDelay(delayMillis, TimeUnit.SECONDS)
                .build();

        // 使用唯一的工作名来标识这个任务
        WorkManager.getInstance(this.getApplication())
                .enqueueUniqueWork(
                        "SendMessageWork",
                        ExistingWorkPolicy.REPLACE, workRequest);
    }
}
